import 'swiper/css'
import './LayoutData.scss'


import { v4 } from 'uuid'
import { useState, useRef, useEffect } from 'react'
import GridLayout from 'react-grid-layout'
import { useEventEmitter, useMount, useSize } from 'ahooks'
import { Spin, Result, FloatButton, Tooltip, App, Dropdown, Button, Popconfirm } from "antd"

import { Http } from '../Utils/Api'
import { TemplateCommon } from './Common'
import { useRequest } from 'alova/client'
import { AdminRouter } from '../Config/default'
import SmallWindow from '../Page/Other/SmallWindow'
import { Encrypt, Decrypt, GetIndexedDB } from '../Utils/IndexedDB'
import { LayoutDeftula } from '../Config/LayoutDeftula'
import { modelStore, drawerStore } from '../Config/zustand'
import { strOfurlParamsFunc, replaceNodeById, ColorCallBack, updateTreeByKey } from '../Utils'


import { Swiper, SwiperSlide } from 'swiper/react'

import {
    BorderlessTableOutlined,
    ApiOutlined,
    LayoutOutlined,
    ProductOutlined,
    SendOutlined,
    ClearOutlined,
    SelectOutlined,
    DeleteOutlined,
    AppstoreAddOutlined,
    SettingOutlined,
    SaveOutlined,
    BorderOutlined,
    SwapOutlined,
    PlusCircleOutlined
} from '@ant-design/icons'

const { port } = window.location

const DropdownSZtyle = {
    '--iconSize': '16px',
    '--iconFilter': 'drop-shadow(1px 1px 1px #262626)',
    '--fontSize': '16px',
    '--fontFamily': 'ShuHeiTi',
    '--fontWeight': 400,
    '--fontStyle': 'normal',
    '--fontFilter': 'drop-shadow(1px 1px 1px #262626)',
}

// 导航模板
const TemplateNav = ({ item, apiData, PageEvent }) => {
    const [optionsStatus, setOptionsStatus] = useState(false)
    const { message, modal, notification } = App.useApp()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { nav, config } = item
    const TempEvent = useEventEmitter()
    const swiperSlideRef = useRef()
    const size = useSize(swiperSlideRef)
    const [swiperRef, setswiperRef] = useState()
    const [LayoutData, setLayoutData] = useState(config)
    const [LayoutStatus, setLayoutStatus] = useState(false)


    const [SIZE, setSIZE] = useState()

    const onActiveLayout = () => {
        console.log('激活布局')
        setLayoutStatus(true)
    }
    const onSaveLayout = (data) => {
        item.config = data || LayoutData
        PageEvent.emit({ type: 'saveModelLayout', data: item })
        setLayoutStatus(false)
    }
    // 新增模板
    const onAddTemp = (item) => {
        const newItem = { i: v4(), x: 0, y: 0, w: 8, h: 8, temp: '', config: {} }
        LayoutData[item.i].push(newItem)
        setLayoutData({ ...LayoutData })
    }

    // 选择模板
    const onSelectTemp = (item, key) => {
        updateModel({ type: 'CommonModel', width: 1200, title: '模块选择', data: { modelId: item.i, tempId: key.i, type: 'customModule', DateEvent: TempEvent } })
    }

    const onSelectTempBack = (data) => {
        const { modelId, tempId, name } = data
        LayoutData[modelId].find(v => v.i === tempId).temp = name
        LayoutData[modelId].find(v => v.i === tempId).config = name.includes('Chart') ? AdminRouter[name] : LayoutDeftula[name]
        setLayoutData({ ...LayoutData })
        onSaveLayout({ ...LayoutData })
    }

    // 配置模板信息
    const onSetTemplate = (item, key) => {
        // if (temp.includes('Chart')) {
        //     updateDrawer({
        //         type: 'CommonCharts',
        //         title: TemplateCommon[temp].title + '配置',
        //         width: 800,
        //         data: {
        //             type: temp,
        //             uuid: i,
        //             Initial: config,
        //             DateEvent: TemplateEvent
        //         }
        //     })
        // } else {
        //     updateDrawer({
        //         type: 'AddFormData',
        //         width: 480,
        //         title: '模板设置',
        //         mask: false,
        //         data: {
        //             type: 'SetTemplateConfig',
        //             config: temp,
        //             AddEvnet: TemplateEvent,
        //             Initial: { ...config, uuid: i }
        //         }
        //     })
        // }
        if (key.temp.includes('Chart')) {
            updateDrawer({
                type: 'CommonCharts',
                title: TemplateCommon[key.temp].title + '配置',
                width: 800,
                data: {
                    type: key.temp,
                    i: key.i,
                    Initial: key.config,
                    DateEvent: TempEvent,
                    onCallBack: item.i
                }
            })
        } else {
            updateDrawer({
                type: 'AddFormData',
                width: 480,
                title: '模板设置',
                mask: false,
                data: {
                    type: 'SetTemplateConfig',
                    config: key.temp,
                    AddEvnet: TempEvent,
                    Initial: { ...key.config, i: key.i },
                    onCallBack: item.i
                }
            })
        }


    }
    const onSetTemplateBack = (data) => {
        const { i, onCallBack, ...obj } = data
        item.config[onCallBack].find(v => v.i === i).config = obj
        setLayoutData(item.config)
        onSaveLayout(item.config)
    }


    // 删除模块
    const onDeleteTemp = (item, key) => {
        const data = LayoutData[item.i].filter(v => v.i !== key.i)
        setLayoutData(e => {
            const obj = { ...e, [item.i]: data }
            notification.success({ message: '删除成功!', description: '模板已删除!', key: 'pageLayout' })
            onSaveLayout(obj)
            return obj
        })
    }

    // 清空布局
    const onClaerModel = (item) => {
        setLayoutData(e => {
            const obj = { ...e, [item.i]: [] }
            notification.success({ message: '清除成功!', description: '模块布局已清空!', key: 'pageLayout' })
            return obj
        })
    }

    // 模块布局改变
    const onLayoutChange = (e, i) => {
        setLayoutData(obj => ({ ...obj, [i]: replaceFields(e, LayoutData, i) }))
    }

    const replaceFields = (arr1, arr2, i) => {
        for (const item2 of arr2[i]) {
            const foundIndex = arr1.findIndex(item1 => item1.i === item2.i)
            if (foundIndex !== -1) {
                arr1[foundIndex].temp = item2.temp
                arr1[foundIndex].config = item2.config
            }
        }
        return arr1
    }

    // 模块布局菜单
    const TemplateItem = (item) => {
        return [
            { key: 0, type: 'group', label: '模块布局' },
            !LayoutStatus &&
            { key: 1, label: (<Button style={DropdownSZtyle} type='link' icon={<LayoutOutlined />} onClick={onActiveLayout}>激活布局</Button>) },
            LayoutStatus &&
            { key: 2, label: (<Button style={DropdownSZtyle} type='link' icon={<SaveOutlined />} onClick={() => onSaveLayout()}>保存布局</Button>) },
            LayoutStatus &&
            { key: 3, label: (<Button style={DropdownSZtyle} type='link' icon={<PlusCircleOutlined />} onClick={() => onAddTemp(item)}>添加模块</Button>) },
            // LayoutStatus[item.i].length !== 0 &&
            LayoutData[item.i].length !== 0 && {
                key: 4,
                label: (
                    <Popconfirm
                        title="清空警告"
                        description="确定清空当前布局吗？"
                        onConfirm={() => onClaerModel(item)}
                        okText="清空"
                        cancelText="取消"
                    >
                        <Button style={DropdownSZtyle} type='link' danger icon={<ClearOutlined />}>清空布局</Button>
                    </Popconfirm>
                )
            },
        ]
    }
    // 模板信息设置
    const TemplateInfo = (item, key) => {
        return [
            { key: 0, type: 'group', label: '模板信息' },
            { key: 1, label: (<Button style={DropdownSZtyle} type='link' icon={<SelectOutlined />} onClick={() => onSelectTemp(item, key)}>选择模板</Button>) },
            key.temp &&
            { key: 2, label: (<Button style={DropdownSZtyle} type='link' icon={<SettingOutlined />} onClick={() => onSetTemplate(item, key)}>配置模板</Button>) },
            {
                key: 3,
                label: (
                    <Popconfirm
                        title="删除警告"
                        description="确定删除当前模板吗？"
                        onConfirm={() => onDeleteTemp(item, key)}
                        okText="删除"
                        cancelText="取消"
                    >
                        <Button style={DropdownSZtyle} type='link' danger icon={<DeleteOutlined />}>删除模板</Button>
                    </Popconfirm>
                )
            },
        ]
    }

    const onOptionsSwitch = (data) => PageEvent.emit({ type: 'onOptionsSwitch', data })

    const CallBackFunc = (e) => {
        const { type, data } = e
        // console.log(type, data)
        const MapReturn = new Map([
            ['onOptionsSwitch', () => onOptionsSwitch(data)],
            ['onFormBack', () => onSetTemplateBack(data)],
            ['onSelectTemp', () => onSelectTempBack(data)],
            // ['saveModelLayout', () => saveModelLayout(data)],
        ])
        const func = MapReturn.get(type)
        return func && func()
    }
    TempEvent.useSubscription(CallBackFunc)
    useEffect(() => { if (size && !SIZE) setSIZE(size) }, [size])

    useMount(async () => {
        const { userUuid } = await GetIndexedDB('user')
        setOptionsStatus(userUuid === '1e99e116-6ec0-425c-87b4-64dd2ce458e2')
    })

    return (
        <div className='TemplateNav'>
            <div className='TemplateNav__nav'>
                {nav.map((item, index) => {
                    const { i, status } = item
                    if (status) {
                        return (
                            <div key={i} onClick={() => { swiperRef.slideTo(index, 0) }}>
                                {item.nav_title} - 导航块 判定显示信息
                            </div>
                        )
                    } else return false
                })}
            </div>
            <Swiper
                ref={swiperRef}
                className='TemplateNav__temp'
                noSwiping={true}
                onSwiper={(swiper) => setswiperRef(swiper)}
            >
                {nav.map((item) =>
                    <SwiperSlide key={item.i} ref={swiperSlideRef}>
                        <Dropdown menu={{ items: (port || optionsStatus) ? TemplateItem(item) : [] }} trigger={['contextMenu']} placement='bottomRight'>
                            <div className='TemplateNav__item swiper-no-swiping' style={{ border: LayoutStatus ? '1px solid #eb2f96' : 'none' }}>
                                {SIZE &&
                                    <GridLayout
                                        isDraggable={LayoutStatus}
                                        isResizable={LayoutStatus}
                                        layout={LayoutData[item.i]}
                                        margin={[0, 0]}
                                        cols={12}
                                        rowHeight={LayoutStatus ? SIZE.height / 12 : size.height / 12}
                                        width={LayoutStatus ? SIZE.width : size.width}
                                        onDragStop={(e) => onLayoutChange(e, item.i)}
                                        onResizeStop={(e) => onLayoutChange(e, item.i)}
                                    >
                                        {LayoutData[item.i].map(key => {
                                            const TemplateComponent = TemplateCommon?.[key.temp]?.temp || ''
                                            return (
                                                <div
                                                    key={key.i}
                                                    className='GridItem'
                                                    style={LayoutStatus ? { border: `1px solid #ccc` } : {}}
                                                >
                                                    <Dropdown
                                                        menu={{ items: (port || optionsStatus) ? TemplateInfo(item, key) : [] }}
                                                        trigger={['contextMenu']}
                                                        placement='bottomLeft'
                                                    >
                                                        {key.temp ?
                                                            <div className='GridTemp'>
                                                                <TemplateComponent config={key.config} TempEvent={TempEvent} apiData={apiData} />
                                                            </div> :
                                                            <div className='GridTemp none'>未选择模板 {key.w}*{key.h}</div>
                                                        }
                                                    </Dropdown>
                                                </div>
                                            )
                                        })}
                                    </GridLayout>
                                }
                            </div>
                        </Dropdown>
                    </SwiperSlide>
                )}
            </Swiper>
        </div>
    )
}

// 小窗模板
const TemplateRender = ({ item, smallWindow, apiData, PageEvent }) => {
    const { nav, model, config } = item
    const { type, smallWindow: smallWindowStatus, smallTitle,
        text, titleText, titleSize, titleColor, titleFamily, titleStyle, titleWeight,
        titleShadowX, titleShadowY, titleShadowS, titleShadowC,
        backColor, backColorDeg, backMargin, backPadding, backRadius, backShadow, background
    } = model

    if (smallWindowStatus) {
        return (
            <SmallWindow config={smallWindow} title={smallTitle}>
                {nav.length !== 0 ?
                    <TemplateNav item={item} PageEvent={PageEvent} apiData={apiData} /> :
                    <div className='WaitingSelection'>未设置导航信息</div>
                }
            </SmallWindow>
        )
    } else {
        const textStyle = {
            color: titleColor,
            fontSize: titleSize,
            fontFamily: titleFamily,
            fontStyle: titleStyle,
            fontWeight: titleWeight,
            filter: `drop-shadow(${titleShadowX}px ${titleShadowY}px ${titleShadowS}px ${titleShadowC})`,
        }
        const backStyle = {
            background: background && ColorCallBack(backColor, backColorDeg),
            margin: backMargin,
            padding: backPadding,
            borderRadius: backRadius,
            boxShadow: backShadow,
        }
        return (
            <div className='OrdinaryModule' style={background ? backStyle : {}}>
                {text && <div className='OrdinaryModule__title' style={textStyle}>{titleText}</div>}
                <div className='OrdinaryModule__content'>
                    {nav.length !== 0 ?
                        <TemplateNav item={item} PageEvent={PageEvent} apiData={apiData} /> :
                        <div className='WaitingSelection'>未设置导航信息</div>
                    }
                </div>
            </div>
        )
    }
}

// 入口函数
const LayoutData = ({ page, smallWindow, router }) => {
    const [optionsStatus, setOptionsStatus] = useState(false)
    const gridRef = useRef(null)
    const size = useSize(gridRef)
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { message, modal, notification } = App.useApp()
    const { send } = useRequest(data => Http(data), { immediate: false })
    const PageEvent = useEventEmitter()
    // 状态参数
    const [Open, setOpen] = useState(false)
    const [Loading, setLoading] = useState(true)
    const [PageStatus, setPageStatus] = useState(false)
    // 数据参数
    const [ApiData, setApiData] = useState([])
    const [ApiList, setApiList] = useState([])
    const [ApiParams, setApiParams] = useState({})
    const [Layout, setLayout] = useState({})
    const [LayoutData, setLayoutData] = useState([])
    const [LayoutStatus, setLayoutStatus] = useState(false)

    // 获取数据
    const getJson = () => {
        send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: `StartConfig/${page}` } }).then(async res => {
            const data = await Decrypt(res)
            const { apiUrl, layout } = data
            // console.log('[-----获取配置-----]', data)
            setLayoutData(layout || [])
            setApiList(apiUrl || [])
            getApiData(data)
            setLayout(data)
            setLoading(false)
            setPageStatus(true)
        }).catch(err => {
            setLoading(false)
        })
    }

    // 保存数据
    const setJson = async (data = {}) => {
        const params = { ...Layout, layout: LayoutData, ...data }
        const content = JSON.stringify(await Encrypt(params))
        // console.log('[-----保存配置------]', params)
        send({ method: 'post', url: 'dictionary/SaveJsonInfoByUuid', params: { uuid: `StartConfig/${page}`, content } }).then(res => {
            notification.success({ message: '数据请求成功!', description: '配置文件保存成功!', key: 'pageLayout' })
            getJson()
        }).catch(err => {
            notification.error({ message: '数据请求失败!', description: err.message, key: 'pageLayout' })
        })
    }

    // 接口数据
    const getAPIDate = async (data, extra) => {
        const { method, url, apiData, path, params } = data
        const apiParams = extra[apiData] ? { ...strOfurlParamsFunc(params), ...extra[apiData] } : { ...strOfurlParamsFunc(params) }
        setApiParams(e => ({ ...e, [apiData]: apiParams }))
        try { return { name: apiData, data: await Http({ method, url, path, params: apiParams }) } }
        catch (err) { notification.error({ message: '数据请求失败!', description: err.message }) }
    }

    const extractParams = (layout) => {
        const options = layout.flatMap(item => Object.values(item.config).flatMap(config => config.filter(v => v.temp.includes('Options'))))
        if (options.length === 0) return {}

        return options.reduce((paramsList, item) => {
            const { urlList, params, value } = item.config
            urlList?.forEach(({ urlName }) => {
                if (!paramsList[urlName]) { paramsList[urlName] = {} }
                paramsList[urlName][params] = encodeURIComponent(value)
            })
            return paramsList
        }, {})
    };

    const getApiData = async (data) => {
        const { apiUrl, layout } = data
        if (apiUrl && apiUrl.length !== 0 && layout?.length !== 0) {
            const options = extractParams(layout)
            const apiData = await Promise.all(apiUrl.map(item => getAPIDate(item, options)))
            setApiData(apiData)
        }
    }

    // 基础设置
    const onBaseConfig = () => {
        updateDrawer({
            type: 'AddFormData',
            width: 480,
            title: '边距设置',
            mask: false,
            data: { type: 'StartPadding', onCallBack: 'base', AddEvnet: PageEvent, Initial: Layout }
        })
    }
    // 接口设置
    const onApiConfig = () => {
        updateDrawer({
            type: 'AddFormData',
            width: 480,
            title: '接口设置',
            mask: false,
            data: { type: 'StartApiUrl', onCallBack: 'api', AddEvnet: PageEvent, Initial: Layout }
        })
    }

    // 激活布局
    const onActiveLayout = () => {
        setLayoutStatus(true)
        message.loading({ content: '布局激活中...', duration: 0, key: 'pageLayout' })
    }

    // 新增模块
    const onAddModel = () => {
        const newItem = { i: v4(), x: 0, y: 0, w: 8, h: 8, nav: [], model: AdminRouter.LayoutModelConfig.model, config: {} }
        setLayoutData(e => ([...e, newItem]))
    }
    // 保存模块
    const onSaveModel = () => {
        setJson()
        setLayoutStatus(false)
        message.success({ content: '布局已结束', key: 'pageLayout' })
    }
    // 清空模块
    const onClearModel = () => {
        setLayoutData(() => {
            setJson({ layout: [] })
            return []
        })
        notification.success({ message: '清除成功!', description: '布局信息已清除!', key: 'pageLayout' })
    }

    // 模块设置
    const onSetModel = (i) => {
        updateDrawer({
            type: 'AddFormData',
            width: 480,
            title: '模块设置',
            mask: false,
            data: { type: 'LayoutSetModel', onCallBack: 'setModel', AddEvnet: PageEvent, Initial: LayoutData.find(v => v.i === i) }
        })
    }
    // 模块导航
    const onSetNavList = (i) => {
        updateDrawer({
            type: 'AddFormData',
            width: 480,
            title: '模块导航',
            mask: false,
            data: { type: 'LayoutSetNav', onCallBack: 'setNav', AddEvnet: PageEvent, Initial: LayoutData.find(v => v.i === i) }
        })

    }

    // 删除模块
    const onDelModel = (i) => {
        setLayoutData(e => {
            const obj = e.filter(v => v.i !== i)
            setJson({ layout: obj })
            notification.success({ message: '删除成功!', description: '模块信息已删除!', key: 'pageLayout' })
            return obj
        })
    }

    // 全局右键菜单
    const GlobalOperation = [
        { key: 0, type: 'group', label: '全局操作' },
        { key: 5, label: (<Button style={DropdownSZtyle} type='link' icon={<BorderlessTableOutlined />} onClick={onBaseConfig}>基础设置</Button>) },
        { key: 6, label: (<Button style={DropdownSZtyle} type='link' icon={<ApiOutlined />} onClick={onApiConfig}>接口设置</Button>) },
        !LayoutStatus && {
            key: 1,
            label: (<Button style={DropdownSZtyle} type='link' icon={<LayoutOutlined />} onClick={onActiveLayout}>激活布局</Button>)
        },
        LayoutStatus && {
            key: 2,
            label: (<Button style={DropdownSZtyle} type='link' icon={<AppstoreAddOutlined />} onClick={onAddModel}>新增模块</Button>)
        },
        LayoutStatus && {
            key: 3,
            label: (<Button style={DropdownSZtyle} type='link' icon={<SaveOutlined />} onClick={onSaveModel}>保存布局</Button>)
        },
        LayoutData.length !== 0 && {
            key: 4,
            label: (
                <Popconfirm
                    title="清空警告"
                    description="确定清空当前布局吗？"
                    onConfirm={onClearModel}
                    okText="清空"
                    cancelText="取消"
                >
                    <Button style={DropdownSZtyle} type='link' icon={<ClearOutlined />} danger>清空布局</Button>
                </Popconfirm>
            )
        },
    ].filter(v => v)
    // 局部右键菜单
    const RegionalOperation = (item) => {
        return [
            { key: 0, type: 'group', label: '模块操作' },
            { key: 1, label: <Button style={DropdownSZtyle} type='link' icon={<SettingOutlined />} onClick={() => onSetModel(item.i)}>模块设置</Button> },
            { key: 2, label: <Button style={DropdownSZtyle} type='link' icon={<SwapOutlined />} onClick={() => onSetNavList(item.i)}>模块导航</Button> },
            {
                key: 7,
                label: (
                    <Popconfirm
                        title="清空警告"
                        description="确定清空当前布局吗？"
                        onConfirm={() => onDelModel(item.i)}
                        okText="清空"
                        cancelText="取消"
                    >
                        <Button style={DropdownSZtyle} type='link' icon={<DeleteOutlined />} danger >删除模块</Button>
                    </Popconfirm>

                )
            },
        ]
    }

    // 表单回调
    const onFormBack = (data) => {
        const { onCallBack, ...rest } = data
        if (onCallBack === 'base' || onCallBack === 'api') {
            setLayout(e => {
                const obj = { ...e, ...rest }
                setJson(obj)
                return obj
            })
            notification.success({ message: '设置成功!', description: `${onCallBack === 'base' ? '基础' : '接口'}信息设置成功!`, key: 'pageLayout' })
        }
        if (onCallBack === 'setModel') {
            const { i, model } = rest
            const tree = JSON.parse(JSON.stringify(LayoutData))
            updateTreeByKey(tree, i, model, 'i', 'model')
            setLayoutData([...tree])
            setJson({ layout: tree })
            notification.success({ message: '设置成功!', description: `模块信息设置成功!`, key: 'pageLayout' })
        }
        if (onCallBack === 'setNav') {
            const { i, nav } = rest
            const newNav = nav.map(item => (item.i ? item : { ...item, i: v4() }))
            const obj = Object.fromEntries(newNav.map(item => [item.i, []]))
            const tree = JSON.parse(JSON.stringify(LayoutData))
            updateTreeByKey(tree, i, newNav, 'i', 'nav')
            updateTreeByKey(tree, i, obj, 'i', 'config')
            setLayoutData([...tree])
            setJson({ layout: tree })
            notification.success({ message: '设置成功!', description: `导航信息设置成功!`, key: 'pageLayout' })
        }
    }

    const saveModelLayout = (data) => {
        const newData = replaceNodeById(Layout.layout, data.i, data, 'i')
        setJson({ layout: newData })
        notification.success({ message: '保存成功!', description: '模块布局已保存!', key: 'pageLayout' })
    }

    // 布局变更信息
    const onLayoutChange = (e) => {
        const data = replaceFields(e, LayoutData)
        setLayoutData(data)
    }

    const replaceFields = (arr1, arr2) => {
        for (const item2 of arr2) {
            const foundIndex = arr1.findIndex(item1 => item1.i === item2.i)
            if (foundIndex !== -1) {
                if (item2.nav !== undefined) arr1[foundIndex].nav = item2.nav
                if (item2.model !== undefined) arr1[foundIndex].model = item2.model
                if (item2.config !== undefined) arr1[foundIndex].config = item2.config
            }
        }
        return arr1
    }

    const onAPIDataUpload = async (data) => {
        const { params, urlList } = data
        const apiUrl = urlList.flatMap(item => ApiList.filter(v => v.apiData === item.urlName))
        urlList.forEach(item => ApiParams[item.urlName] = { ...ApiParams[item.urlName], ...params })
        const apiData = await Promise.all(apiUrl.map(item => getAPIDate(item, ApiParams)))
        apiData.forEach(item => ApiData.find(v => v.name === item.name).data = item.data)
        setApiData([...ApiData])
    }

    const CallBackFunc = (e) => {
        const { type, data } = e
        // console.log(type, data)
        const MapReturn = new Map([
            ['onFormBack', () => onFormBack(data)],
            ['saveModelLayout', () => saveModelLayout(data)],
            ['onOptionsSwitch', () => onAPIDataUpload(data)]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }
    PageEvent.useSubscription(CallBackFunc)
    useMount(async () => {
        getJson()
        const { userUuid } = await GetIndexedDB('user')
        setOptionsStatus(userUuid === '1e99e116-6ec0-425c-87b4-64dd2ce458e2')
    })
    return (
        <div className='LayoutData'>
            {Loading ?
                <Spin size="large" /> :
                PageStatus ?
                    <div
                        className='LayoutPage'
                        style={{ padding: `${Layout?.padding?.top}px ${Layout?.padding?.right}px ${Layout?.padding?.bottom}px ${Layout?.padding?.left}px` }}
                    >
                        <Dropdown menu={{ items: (port || optionsStatus) ? GlobalOperation : [] }} trigger={['contextMenu']} placement='topRight'>
                            <div className='GridLayout' ref={gridRef} style={{ border: LayoutStatus ? '1px solid #eb2f96' : 'none' }} >
                                {size &&
                                    <GridLayout
                                        isDraggable={LayoutStatus}
                                        isResizable={LayoutStatus}
                                        layout={LayoutData}
                                        margin={[0, 0]}
                                        cols={24}
                                        rowHeight={size.height / 24}
                                        width={size.width}
                                        onDragStop={onLayoutChange}
                                        onResizeStop={onLayoutChange}
                                    >
                                        {LayoutData.map(item => {
                                            return (
                                                <div
                                                    key={item.i}
                                                    className='GridItem'
                                                    style={LayoutStatus ? { border: `1px solid #ccc` } : {}}
                                                >
                                                    <Dropdown
                                                        menu={{ items: (port || optionsStatus) ? RegionalOperation(item) : [] }}
                                                        trigger={['contextMenu']}
                                                        placement='topLeft'
                                                    >
                                                        <div className='GridTemp'>
                                                            {LayoutStatus && <div className='GridSize'>{`${item.w}*${item.h}`}</div>}
                                                            <TemplateRender item={item} smallWindow={smallWindow} apiData={ApiData} PageEvent={PageEvent} />
                                                        </div>
                                                    </Dropdown>
                                                </div>
                                            )
                                        })}
                                    </GridLayout>
                                }
                            </div>
                        </Dropdown>
                    </div > :
                    <Result
                        status="404"
                        title={`当前页面 ${page} 开发中... `}
                        extra={(port || optionsStatus) && <Button type="primary" key="console" onClick={onBaseConfig}>配置基础参数</Button>}
                    />
            }
        </div >
    );
};

export default LayoutData;